<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/4/5
 * Time: 9:53
 */

namespace app\api\service;


use think\Cache;
use think\Exception;

class AccessToken
{
    //获取和管理access_token

    private $tokenUrl;
    const TOKEN_CACHED_KEY = 'access';
    const TOKEN_EXPIRE_IN = 7000;

    function __construct()
    {
        $url = config('wx.access_token_url');
        $url = sprintf($url, config('wx.app_id'), config('wx.app_secret'));
        $this->tokenUrl = $url;
    }

    //建议用户规模较小时，直接去微信服务器获取最新的token
    // 但微信access_token 接口的获取次数是有限的 2000次/天
    public function get(){
        $token = $this->getFromCache();
        if (!$token){
            return $this->getFromServer();
        }else{
            return $token;
        }
    }

    // 从缓存中获取access_token
    private function getFromCache(){
        $token = Cache::get(self::TOKEN_CACHED_KEY);
        if ($token){
            return $token;
        }
        return null;
    }

    // 从微信服务器获取access_token
    private function getFromServer(){
        $token = curl_get($this->tokenUrl);
        $token = json_decode($token, true);
        if (!$token){
            throw new Exception('获取access_token失败');
        }
        if (!empty($token['errcode'])){
            throw new Exception($token['errmsg']);
        }
        $this->saveToCache($token);
        return $token;
    }

    private function saveToCache($token){
        Cache::set(self::TOKEN_CACHED_KEY, $token, self::TOKEN_EXPIRE_IN);
    }
}